/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.theHead;

//Need the following import to get access to the app resources, since this
//class is in a sub-package.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


/**
 * A list view example where the data comes from a custom ListAdapter
 */
public class Overview extends Activity {

	HeadCursorAdapter cursorAdapter;
	TeamDBAdapter teamDB;
	Cursor c;
	ListView lv;
	Context thisContext;
	int selection = 0;

	public HeadChangeReceiver receiver = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.listview);

		thisContext = this;

		lv = (ListView) findViewById(R.id.ListView);
		Log.i("ricusdebug", "lv found");
		teamDB = new TeamDBAdapter(this);
		teamDB.open();

		c = teamDB.getAllInfo();

		Log.i("listview", "nr cursor results: " + c.getCount());
		cursorAdapter = new HeadCursorAdapter(this, c);
		lv.setAdapter(cursorAdapter);

		lv.setOnItemClickListener(new OnItemClickListener(){
			public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
				final int slectionID = (int) id;
				AlertDialog.Builder dialog = new AlertDialog.Builder(thisContext);
				
				dialog.setTitle(((TextView) view.findViewById(R.id.listItemTeamName)).getText());
				dialog.setCancelable(false);
				dialog.setPositiveButton("Live", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						Intent intent;
						intent = new Intent(thisContext, TeamData.class);
						intent.putExtra("teamID", (int) slectionID);
						thisContext.startActivity(intent);
					}
				});
				dialog.setNeutralButton("Info", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						Intent intent;
						intent = new Intent(thisContext, TeamView.class);
						intent.putExtra("teamID", (int) slectionID);
						thisContext.startActivity(intent);
					}
				});
				dialog.setNegativeButton("Close", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
					}
				});
				dialog.show();
			}
		});
	}

	public void onResume(){
		super.onResume();

		IntentFilter filter;
		filter = new IntentFilter(BackgroundService.NEW_HEAD_DATA	);
		receiver = new HeadChangeReceiver();
		registerReceiver(receiver, filter);
	}

	public void onPause(){
		super.onPause();
		Log.i("ListView", "onPause");
	}

	public void onStop(){
		super.onPause();
		Log.i("ListView", "onStop");
	}

	public void onDestroy(){
		super.onDestroy();

		Log.i("ListView", "onDestroy");
		c.close();
		teamDB.close();

		unregisterReceiver(receiver);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.spectator_menu, menu);
		menu.removeItem(R.id.gotoListView);
		menu.removeItem(R.id.gotoRowMode);
		menu.removeItem(R.id.gotoQuit);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;

		// Handle item selection
		switch (item.getItemId()) {
		case R.id.gotoMapView:
			intent = new Intent(thisContext, ViewMap.class);
			thisContext.startActivity(intent);
			return true;
		case R.id.gotoRowMode:
			intent = new Intent(thisContext, RowmodeIntro.class);
			thisContext.startActivity(intent);
			return true;
		case R.id.gotoListView:
			intent = new Intent(thisContext, Overview.class);
			thisContext.startActivity(intent);
			return true;
		case R.id.gotoQuit:
			//TODO goes back to previous Activity
//			finish();
		default:
			return super.onOptionsItemSelected(item);
		}
	}


	public class HeadChangeReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getIntExtra(BackgroundService.HEAD_DATA_CHANGED, 0)== BackgroundService.READINGS_TABLE_UPDATED){
				Log.i("ListView", "ReadingsTable changed, updating!");
				c.requery();
				cursorAdapter.notifyDataSetChanged();
			}
		}
	}

	public class HeadCursorAdapter extends CursorAdapter {
		public HeadCursorAdapter(Context context, Cursor c) {
			super(context, c);
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			TextView teamNameField;
			TextView strokeField;
			TextView speedField;
			ImageView imageField;

			teamNameField = (TextView) view.findViewById(R.id.listItemTeamName);
			teamNameField.setText(cursor.getString(cursor.getColumnIndex("teamName")));

			strokeField = (TextView) view.findViewById(R.id.listItemStrokeRate);
			strokeField.setText(cursor.getString(cursor.getColumnIndex("tempo")));

			speedField = (TextView) view.findViewById(R.id.listItemSpeed);
			speedField.setText(cursor.getString(cursor.getColumnIndex("speed")));

			int drawable = getResources().getIdentifier(cursor.getString(cursor.getColumnIndex("clubID")).toLowerCase(), "drawable", "android.theHead");
			imageField = (ImageView) view.findViewById(R.id.listImage);
			imageField.setImageResource(drawable);
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			LayoutInflater inflater = LayoutInflater.from(context);
			View v = inflater.inflate(R.layout.list_item, parent, false);
			bindView(v, context, cursor);
			return v;
		}
	}
}
